// fileDownloader.js
import {
	getToken
} from '@/utils/auth';
import {
	toast,
	showConfirm,
	showLoad
} from '@/utils/common.js';
class FileDownloader {
	constructor(options = {}) {
		this.options = {
			baseURL: options.baseURL || '',
			timeout: options.timeout || 10000,
			...options
		};
	}

	/**
	 * 下载并预览文件
	 * @param {string} url - 请求地址
	 * @param {Object} data - 请求参数
	 * @param {string} fileName - 文件名
	 * @param {string} fileType - 文件类型
	 * @param {Object} headers - 自定义请求头
	 */
	async downloadAndPreview({
		url,
		data = {},
		fileName = '下载文件',
		fileType = 'xlsx',
		headers = {}
	}) {
		this.showLoad('资源下载中...');

		try {
			// 1. 请求文件流
			const arrayBuffer = await this.requestFileStream(url, data, headers);

			// 2. 保存为临时文件
			const filePath = await this.saveFile(arrayBuffer, fileName);

			// 3. 预览文件
			await this.previewFile(filePath, fileType);

			return filePath;
		} catch (error) {
			uni.showToast({
				title: error.message || '下载失败',
				icon: 'none',
				duration: 2000
			});
			this.closeLoad()
			throw error;
		}
	}

	/**
	 * 仅下载文件不预览
	 */
	async downloadOnly({
		url,
		data = {},
		fileName = '下载文件',
		headers = {}
	}) {
		this.showLoad('文件下载中...');

		try {
			const arrayBuffer = await this.requestFileStream(url, data, headers);
			const filePath = await this.saveFile(arrayBuffer, fileName);

			uni.showToast({
				title: '下载成功',
				icon: 'success',
				duration: 1500
			});

			return filePath;
		} catch (error) {
			console.error('文件下载失败:', error);
			uni.showToast({
				title: error.message || '下载失败',
				icon: 'none',
				duration: 2000
			});
			this.closeLoad()
			throw error;
		}
	}

	/**
	 * 请求文件流
	 */
	requestFileStream(url, data = {}, customHeaders = {}) {
		return new Promise((resolve, reject) => {
			const fullUrl = url.startsWith('http') ? url : `${this.options.baseURL}${url}`;

			uni.request({
				url: fullUrl,
				method: 'POST',
				data,
				header: {
					'Authorization': 'Bearer ' + getToken(),
					'Content-Type': 'application/json',
					...customHeaders
				},
				responseType: 'arraybuffer',
				timeout: this.options.timeout,
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(new Error(`请求失败，状态码: ${res.statusCode}`));
					}
				},
				fail: (error) => {
					reject(new Error('网络请求失败'));
				}
			});
		});
	}

	/**
	 * 保存文件
	 */
	saveFile(arrayBuffer, fileName) {
		return new Promise((resolve, reject) => {
			// 确保在微信小程序环境中
			if (typeof wx === 'undefined' || !wx.getFileSystemManager) {
				reject(new Error('当前环境不支持文件操作'));
				return;
			}

			const fs = wx.getFileSystemManager();

			// 处理文件名，确保有正确的扩展名
			const processedFileName = this.processFileName(fileName);
			const filePath = `${wx.env.USER_DATA_PATH}/${processedFileName}`;

			fs.writeFile({
				filePath,
				data: arrayBuffer,
				encoding: 'binary',
				success: () => resolve(filePath),
				fail: (error) => {
					reject(new Error('文件保存失败'));
				}
			});
		});
	}

	/**
	 * 预览文件
	 */
	previewFile(filePath, fileType = 'xlsx') {
		return new Promise((resolve, reject) => {
			if (typeof wx === 'undefined' || !wx.openDocument) {
				reject(new Error('当前环境不支持文件预览'));
				return;
			}
			wx.openDocument({
				showMenu: true,
				filePath,
				fileType: this.mapFileType(fileType),
				success: resolve,
				fail: (error) => {
					reject(new Error('文件打开失败'));
				}
			});
		});
	}

	/**
	 * 处理文件名
	 */
	processFileName(fileName) {
		if (!fileName.includes('.')) {
			// 如果没有扩展名，默认添加.xlsx
			return `${fileName}.xlsx`;
		}
		return fileName;
	}

	/**
	 * 映射文件类型
	 */
	mapFileType(fileType) {
		const typeMap = {
			'xlsx': 'xlsx',
			'xls': 'xlsx',
			'doc': 'word',
			'docx': 'word',
			'ppt': 'ppt',
			'pptx': 'ppt',
			'pdf': 'pdf',
			'txt': 'text'
		};

		return typeMap[fileType.toLowerCase()] || 'xlsx';
	}

	/**
	 * 显示加载提示
	 */
	showLoad(title = '加载中...') {
		uni.showLoading({
			title,
			mask: true
		});
	}

	/**
	 * 关闭加载提示
	 */
	closeLoad() {
		uni.hideLoading();
	}
}

// 创建默认实例
const fileDownloader = new FileDownloader({
	baseURL: 'https://www.daolangtongge.com/read-book-api'
});

// 导出默认实例和类
export default fileDownloader;
export {
	FileDownloader
};